package DianShang_2024.ds_02.extract

import org.apache.hudi.DataSourceWriteOptions.{PARTITIONPATH_FIELD, PRECOMBINE_FIELD, RECORDKEY_FIELD}
import org.apache.hudi.QuickstartUtils.getQuickstartWriteConfigs
import org.apache.spark.sql.functions.{col, date_format, greatest, lit}
import org.apache.spark.sql.{SparkSession, functions}

import java.text.SimpleDateFormat
import java.util.{Calendar, Properties}

object extract05 {
  def main(args: Array[String]): Unit = {
    /*
         5、抽取shtd_store库中order_info的增量数据进入Hudi的ods_ds_hudi库中表order_info，根据ods_ds_hudi.order_info表中operate_time或
         create_time作为增量字段(即MySQL中每条数据取这两个时间中较大的那个时间作为增量字段去和ods里的这两个字段中较大的时间进行比较)，只将新增的数据抽
         入，字段名称、类型不变，同时添加分区，分区字段为etl_date，类型为String，且值为当前比赛日的前一天日期（分区字段格式为yyyyMMdd）。id作
         为primaryKey，operate_time作为preCombineField。使用spark-shell执行show partitions ods_ds_hudi.order_info命令，将结果截图粘贴至
         客户端桌面【Release\任务B提交结果.docx】中对应的任务序号下；
     */
    val spark=SparkSession.builder()
      .master("local[*]")
      .appName("数据抽取第五题")
      .config("hive.exec.dynamic.mode","nonstrict")
      .config("spark.serializer","org.apache.spark.serializer.KryoSerializer")
      .config("spark.sql.extensions","org.apache.spark.sql.hudi.HoodieSparkSessionExtension")
      .enableHiveSupport()
      .getOrCreate()

      spark.sql("use ods_ds_hudi02")

    val order_info_path="hdfs://192.168.40.110:9000/user/hive/warehouse/ods_ds_hudi02.db/order_info"

    val mysql_connect=new Properties()
    mysql_connect.setProperty("user","root")
    mysql_connect.setProperty("password","123456")
    mysql_connect.setProperty("driver","com.mysql.jdbc.Driver")


    val max_time=spark.read.format("hudi").load(order_info_path)
      .agg(functions.max(greatest(col("create_time"),col("operate_time"))))
      .first()
      .get(0)
      .toString

    println("最大的时间为:",max_time)

    val day:Calendar=Calendar.getInstance()
    day.add(Calendar.DATE,-1)
    val yesterday=new SimpleDateFormat("yyyyMMdd").format(day.getTime)
    println("昨天的日期:",yesterday)


    spark.read.jdbc("jdbc:mysql://192.168.40.110:3306/shtd_store?useSSL=false","order_info",mysql_connect)
      .where(
         greatest(col("create_time"),col("operate_time")) > lit(max_time).cast("timestamp")
      )
      .withColumn(
        "create_time",date_format(col("create_time"),"yyyy-MM-dd HH:mm:ss")
      )
      .withColumn(
        "operate_time",date_format(col("operate_time"),"yyyy-MM-dd HH:mm:ss")
      )
      .withColumn("expire_time",date_format(col("expire_time"),"yyyy-MM-dd HH:mm:ss"))
      .withColumn("etl_date",lit(yesterday))
      .write.mode("append")
      .format("hudi")
      .options(getQuickstartWriteConfigs)
      .option(RECORDKEY_FIELD.key(),"id")
      .option(PRECOMBINE_FIELD.key(),"operate_time")
      .option(PARTITIONPATH_FIELD.key(),"etl_date")
      .option("hoodie.table.name","order_info")
      .save(order_info_path)



    spark.close()
  }

}
